package com.watson;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.watson.activity.RegisterActivity;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.DialogUitl;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends Base2Activity implements View.OnClickListener {
    private long mExitTime = 0;//退出程序
    private AppCompatButton login_btn;
    private ImageView imgMima, imgEye;
    private LinearLayout lyMima, lySn, lyZhang;
    private TextView tvZhang, tvSn, edSn;
    private RelativeLayout rlLayout;
    private String userName, password, snStr;
    private EditText ed_userName, ed_password;
    private boolean isMima = false;
    private boolean isEye = false;
    private boolean isType;

    private boolean isLogin = true;//true：账号登录，false：SN登录

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        statusbar4();
        requestPermission();
    }

    private void initView() {
        imgEye = findViewById(R.id.imgEye);
        lyMima = findViewById(R.id.lyMima);
        imgMima = findViewById(R.id.imgMima);
        login_btn = findViewById(R.id.login_btn);
        ed_userName = findViewById(R.id.ed_userName);
        ed_password = findViewById(R.id.ed_password);
        rlLayout = findViewById(R.id.rlLayout);
        lySn = findViewById(R.id.lySn);
        lyZhang = findViewById(R.id.lyZhang);
        tvZhang = findViewById(R.id.tvZhang);
        tvSn = findViewById(R.id.tvSn);
        edSn = findViewById(R.id.edSn);
        tvZhang.setTextColor(getResources().getColor(R.color.bg_main));
        tvSn.setTextColor(getResources().getColor(R.color.tv333));
        lyZhang.setVisibility(View.VISIBLE);
        lySn.setVisibility(View.GONE);
        isLogin = true;

        lyMima.setOnClickListener(this);
        login_btn.setOnClickListener(this);

        userName = SPUtils.get(mContext, "userName", "") + "";
        password = SPUtils.get(mContext, "password", "") + "";
        isType = (Boolean) SPUtils.get(mContext, "isType", false);
        rlLayout.setOnClickListener(v -> StringUtils.hintKeyBoard(mContext, rlLayout));

        if (!StringUtils.isEmpty(userName)) {
            ed_userName.setText(userName);
        }

        if (isType) {
            isMima = true;
            imgMima.setBackground(getResources().getDrawable(R.mipmap.mima_seletd));
            if (!StringUtils.isEmpty(password)) {
                ed_password.setText(password);
            }
        } else {
            isMima = false;
            imgMima.setBackground(getResources().getDrawable(R.mipmap.mima));
        }

        imgEye.setOnClickListener(v -> {
            if (isEye) {
                isEye = false;
                ed_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                imgEye.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_eye_b));
            } else {
                isEye = true;
                ed_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                imgEye.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_eye_z));
            }
        });

        tvSn.setOnClickListener(v -> {
            edSn.setText(StringUtils.getDeviceSN(mContext) + "");
            tvZhang.setTextColor(getResources().getColor(R.color.tv333));
            tvSn.setTextColor(getResources().getColor(R.color.bg_main));
            lyZhang.setVisibility(View.GONE);
            lySn.setVisibility(View.VISIBLE);
            isLogin = false;
        });

        tvZhang.setOnClickListener(v -> {
            tvZhang.setTextColor(getResources().getColor(R.color.bg_main));
            tvSn.setTextColor(getResources().getColor(R.color.tv333));
            lyZhang.setVisibility(View.VISIBLE);
            lySn.setVisibility(View.GONE);
            isLogin = true;
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lyMima:
                if (isMima) {
                    isMima = false;
                    imgMima.setBackground(getResources().getDrawable(R.mipmap.mima));
                } else {
                    isMima = true;
                    imgMima.setBackground(getResources().getDrawable(R.mipmap.mima_seletd));
                }
                break;

            case R.id.login_btn:
                if (isLogin) {
                    userName = ed_userName.getText().toString().trim();
                    if (StringUtils.isEmpty(userName)) {
                        ToastUtil.show("请输入账号!");
                        return;
                    }
                    password = ed_password.getText().toString().trim();
                    if (StringUtils.isEmpty(password)) {
                        ToastUtil.show("请输入密码!");
                        return;
                    }

                    loginData(userName, password, "");
                } else {
                    snStr = edSn.getText().toString().trim();
                    if (StringUtils.isEmpty(snStr)) {
                        ToastUtil.show("SN号不能为空!");
                        return;
                    }

                    loginData("", "", snStr);
                }
                break;
        }
    }

    private void loginData(String account, String pwd, String sn) {
        login_btn.setEnabled(false);

        HttpClient.getInstance().getData(CommonHttpConsts.login, "login")
                .params("username", account)
                .params("pwd", pwd)
                .params("SN", sn)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.show(msg);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            Map dataMap = JSON.parseObject(info, Map.class);
                            if (!dataMap.isEmpty()) {
                                Map loginData = new HashMap();
                                loginData = JSON.parseObject(dataMap.get("Logindata") + "", Map.class);
                                if (loginData.size() > 0) {
                                    SPUtils.put(mContext, "U_Id", loginData.get("U_Id") + "");
                                    SPUtils.put(mContext, "U_Name", loginData.get("U_Name") + "");//用户名
                                    SPUtils.put(mContext, "R_ID", loginData.get("R_ID") + "");
                                    SPUtils.put(mContext, "U_LOGIN_NAME", loginData.get("U_LOGIN_NAME") + "");//登录名
                                    SPUtils.put(mContext, "U_DEPARTMENT", loginData.get("U_DEPARTMENT") + "");//归属部门
                                    SPUtils.put(mContext, "U_BRAND", loginData.get("U_BRAND") + "");//品牌
                                    SPUtils.put(mContext, "U_CODE", loginData.get("U_CODE") + "");
                                    SPUtils.put(mContext, "url", loginData.get("url") + "");
                                    SPUtils.put(mContext, "U_ERP_ACCOUNT", loginData.get("U_ERP_ACCOUNT") + "");
                                    SPUtils.put(mContext, "token", loginData.get("token") + "");//token码
                                    SPUtils.put(mContext, "warehouse", loginData.get("warehouse") + "");//仓库
                                    SPUtils.put(mContext, "fun", loginData.get("fun") + "");//功能权限编码
                                    SPUtils.put(mContext, "auth", loginData.get("auth") + "");//按键权限ID
                                    SPUtils.put(mContext, "standing", loginData.get("standing") + "");//身份standing身份，0普通用户，1管理员
                                    SPUtils.put(mContext, "barcoderules", loginData.get("barcoderules") + "");//库位码

//                                    SPUtils.put(mContext, "U_DEPOT_ID", loginData.get("U_DEPOT_ID"));
//                                    SPUtils.put(mContext, "U_DEPOT_NAME", loginData.get("U_DEPOT_NAME"));
//                                    SPUtils.put(mContext, "R_Fun_Id", loginData.get("R_Fun_Id"));//页面权限ID
//                                    SPUtils.put(mContext, "R_Auth_Code", loginData.get("R_Auth_Code"));//功能权限编码
                                }
                                ArrayList<Map> numberRuleList = new ArrayList<>();
                                numberRuleList = (ArrayList<Map>) JSON.parseArray(dataMap.get("numberRuleList") + "", Map.class);
                                if (numberRuleList.size() > 0) {
                                    SPUtils.put(mContext, "numberRuleList", dataMap.get("numberRuleList"));
                                    //凸机识别号编码规则，接口返回按照优先级倒叙排序输出
                                    for (int i = 0; i < numberRuleList.size(); i++) {
                                        SPUtils.put(mContext, "EngineCodeLenth_" + i, numberRuleList.get(i).get("EngineCodeLenth"));//凸机识别号长度
                                        SPUtils.put(mContext, "TypeCodeLenth_" + i, numberRuleList.get(i).get("TypeCodeLenth"));//机型代码长度
                                        SPUtils.put(mContext, "TypeCodeIndex_" + i, numberRuleList.get(i).get("TypeCodeIndex"));//机型代码索引开始位置
                                        SPUtils.put(mContext, "DateCodingLenth_" + i, numberRuleList.get(i).get("DateCodingLenth"));//日期时间长度
                                        SPUtils.put(mContext, "DateCodingIndex_" + i, numberRuleList.get(i).get("DateCodingIndex"));//日期时间索引开始位置
                                        SPUtils.put(mContext, "FactoryCodeLenth_" + i, numberRuleList.get(i).get("FactoryCodeLenth"));//供应商编号长度
                                        SPUtils.put(mContext, "FactoryCodeIndex_" + i, numberRuleList.get(i).get("FactoryCodeIndex"));//供应商编号索引开始位置
                                        SPUtils.put(mContext, "SerialNumberLenth_" + i, numberRuleList.get(i).get("SerialNumberLenth"));//流水号长度
                                        SPUtils.put(mContext, "SerialNumberIndex_" + i, numberRuleList.get(i).get("SerialNumberIndex"));//流水号索引开始位置
                                        SPUtils.put(mContext, "IsUsable_" + i, numberRuleList.get(i).get("IsUsable"));//是否验证工厂
                                        SPUtils.put(mContext, "Priority_" + i, numberRuleList.get(i).get("Priority"));//凸机识别号编码规则优先级

                                        String OverTime = numberRuleList.get(i).get("OverTime") + "";
                                        if (!StringUtils.isEmpty(OverTime)) {
                                            SPUtils.put(mContext, "OverTime_" + i, StringUtils.isInteger(OverTime.replaceFirst("^0+(?!$)", "")) + "");
                                        } else {
                                            SPUtils.put(mContext, "OverTime_" + i, "");
                                        }
                                    }
                                }

                                SPUtils.put(mContext, "isType", isMima);
                                SPUtils.put(mContext, "userType", true);
                                if (isLogin) {
                                    SPUtils.put(mContext, "userName", userName);
                                    SPUtils.put(mContext, "password", password);
                                } else {
                                    SPUtils.put(mContext, "sn", snStr);
                                }
                                startActivity(new Intent(mContext, MainActivity.class));
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                        ToastUtil.show("网络异常请稍后再试！");
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        login_btn.setEnabled(true);
                    }
                });
    }

    public void onRegisterClick(View v) {
        Intent intent = new Intent(mContext, RegisterActivity.class);
        startActivity(intent);
    }


    private static final int MY_PERMISSION_REQUEST_CODE = 10000;

    private void requestPermission() {
        /**
         * 第 1 步: 检查是否有相应的权限
         */
        boolean isAllGranted = checkPermissionAllGranted(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.CAMERA, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION});

        // 如果这个权限全都拥有, 则直接执行备份代码
        if (isAllGranted) {
            return;
        }

        /**
         * 第 2 步: 请求权限
         */
        // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.CAMERA, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_CODE);
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                // 如果所有的权限都授予了, 则执行备份代码
                return;
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
//                openAppDetails();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
